package com.yugao.fintech.draper.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.draper.admin.convert.UserConvert;
import com.yugao.fintech.draper.admin.entity.*;
import com.yugao.fintech.draper.admin.mapper.UserMapper;
import com.yugao.fintech.draper.admin.param.UserQuery;
import com.yugao.fintech.draper.admin.service.*;
import com.yugao.fintech.draper.admin.param.UserInfo;
import com.yugao.fintech.draper.auth.dto.UserInfoVO;
import com.yugao.fintech.draper.datascope.annotation.DataScope;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.yugao.fintech.draper.core.constant.RedisKeyConstants.CACHE_PREFIX_USER_KEY;

@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {
    @Autowired
    private UserPostService userPostService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private TenantService tenantService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public IPage<UserInfoVO> pageQuery(UserQuery userPageDTO) {
        Page<UserInfoVO> pageInfo = UserConvert.INSTANCE.convert(baseMapper.findUserDetailPage(Page.of(userPageDTO.getPageNum(), userPageDTO.getPageSize()), userPageDTO));
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfoVO createUser(UserInfoVO user) {
        // 校验租户账号额度
        tenantService.validCount();
        // 设置用户默认头像
        user.setAvatar(SysUser.DEFAULT_AVATAR);
        // 设置用户密码
        user.setPassword((Objects.isNull(user.getPassword()) ? passwordEncoder.encode(SysUser.DEFAULT_PASSWORD)
                : passwordEncoder.encode(user.getPassword())));
        // 保存用户信息
        SysUser userDO = UserConvert.INSTANCE.convert(user);
        baseMapper.insert(userDO);
        Long userId = userDO.getUserId();
        user.setUserId(userId);
        // 保存用户角色
        setUserRoles(user);
        // 保存用户岗位
        setUserPosts(user);
        return user;
    }

    @CacheEvict(value = CACHE_PREFIX_USER_KEY, key = "#user.userId")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserInfoVO user) {
        // 更新用户基础信息
        updateUserInfo(user);
        // todo 判断不应根据头像来判断
        if (StrUtil.isBlank(user.getAvatar())) {
            // 根据用户id删除用户角色信息
            userRoleService.deleteUserRolesByUserIds(Collections.singletonList(user.getUserId().toString()));
            // 根据用户id删除用户岗位信息
            userPostService.remove(Wrappers.<SysUserPost>lambdaQuery().eq(SysUserPost::getUserId, user.getUserId()));
            // 保存角色信息
            setUserRoles(user);
            // 保存岗位信息
            setUserPosts(user);
        }
    }

    @CacheEvict(value = CACHE_PREFIX_USER_KEY, key = "#user.userId")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(UserInfoVO user) {
        // 更新用户
        if (StrUtil.isNotBlank(user.getPassword())) {
            user.setPassword("{bcrypt}" + passwordEncoder.encode(user.getPassword()));
        } else {
            user.setPassword(null);
        }
        user.setUsername(null);
        baseMapper.updateById(UserConvert.INSTANCE.convert(user));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByUserIds(String[] userIds) {
        // 删除用户
        baseMapper.deleteBatchIds(Arrays.asList(userIds));
        // 删除用户角色
        userRoleService.deleteUserRolesByUserIds(Arrays.asList(userIds));
    }

    /**
     * 根据用户id获取用户信息
     */
    @Cacheable(value = CACHE_PREFIX_USER_KEY, key = "#id", unless = "#result==null")
    @Override
    public UserInfoVO findUserById(Long id) {
        SysUser sysUser = baseMapper.findUserById(id);
        return UserConvert.INSTANCE.convert(sysUser);
    }

    /**
     * 通过用户名查找用户信息
     */
    @DataScope(enable = false)
    @Cacheable(value = CACHE_PREFIX_USER_KEY, key = "#username")
    @Override
    public UserInfoVO findByUserName(String username) {
        SysUser sysUser = baseMapper.findByName(username);
        return UserConvert.INSTANCE.convert(sysUser);
    }

    /**
     * 获取用户全部信息
     */
    @Override
    public UserInfo findUserInfo(UserInfoVO userDTO) {
        UserInfo userInfo = new UserInfo();
        // 设置用户信息
        userInfo.setSysUser(userDTO);
        // 查询用户角色信息
        List<SysUserRole> sysUserRoleList = userRoleService.getUserRoleByUserId(userDTO.getUserId());
        if (CollectionUtil.isEmpty(sysUserRoleList)) {
            return userInfo;
        }

        // 查询角色菜单信息
        List<Long> roleIds = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        List<SysRoleMenu> sysRoleMenuList = roleMenuService.getRoleMenuByRoleIds(roleIds);
        if (CollectionUtil.isEmpty(sysRoleMenuList)) {
            return userInfo;
        }

        // 查询菜单信息
        List<Long> menuIds = sysRoleMenuList.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        LambdaQueryWrapper<SysMenu> wrapper = Wrappers.<SysMenu>lambdaQuery().in(SysMenu::getId, menuIds);
        List<SysMenu> sysMenuList = menuService.list(wrapper);
        if (CollectionUtil.isEmpty(sysMenuList)) {
            return userInfo;
        }

        // 设置用户权限标识
        List<String> permissions = sysMenuList.stream().map(SysMenu::getPerms).distinct().collect(Collectors.toList());
        userInfo.setPermissions(permissions);
        return userInfo;
    }

    /**
     * 通过手机号查找用户信息
     *
     * @param mobile 手机号
     * @return 用户信息
     */
    @Override
    public UserInfoVO findByMobile(String mobile) {
        SysUser sysUser = baseMapper.findByMobile(mobile);
        return UserConvert.INSTANCE.convert(sysUser);
    }

    /**
     * 获取当前租户下的所有用户数
     *
     * @return 当前租户下的所有用户数
     */
    @Override
    public long count() {
        return baseMapper.selectCount(Wrappers.emptyWrapper());
    }

    /**
     * 保存用户的岗位信息
     *
     * @param user 用户信息
     */
    private void setUserPosts(UserInfoVO user) {
        if (StrUtil.isBlank(user.getPostId())) {
            return;
        }
        List<SysUserPost> list = Arrays.stream(user.getPostId().split(StringPool.COMMA)).map(postId -> {
            SysUserPost up = new SysUserPost();
            up.setUserId(user.getUserId());
            up.setPostId(Long.valueOf(postId));
            return up;
        }).collect(Collectors.toList());
        userPostService.saveBatch(list);
    }

    /**
     * 保存用户的角色信息
     *
     * @param user 用户信息
     */
    private void setUserRoles(UserInfoVO user) {
        if (StrUtil.isBlank(user.getRoleId())) {
            return;
        }
        List<SysUserRole> list = Arrays.stream(user.getRoleId().split(StringPool.COMMA)).map(roleId -> {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(user.getUserId());
            ur.setRoleId(Long.valueOf(roleId));
            return ur;
        }).collect(Collectors.toList());
        userRoleService.addUserRoles(list);
    }
}